#include"log_mgr.h"
using namespace util;

time_t LogMgr::e, LogMgr::s;
struct tm * LogMgr::timeinfo; 
int LogMgr::log_id;
fstream* LogMgr::log_file;

void LogMgr::init(int argc, const char* argv[]){
#ifdef LOG_ON
	string dir(LOG_DIR);
	log_file = new fstream(dir + "log_id.txt", fstream::in);
	*log_file >> log_id;
	log_file->close();
	delete[] log_file;
	log_id++;
	log_file = new fstream(dir + "log_id.txt", fstream::out);
	*log_file << log_id;
	log_file->close();
	delete[] log_file;
	stringstream st;
	string log_name;
	st << log_id << ".txt";
	st >> log_name;
	log_file = new fstream(dir + log_name, fstream::out);
	*log_file << "args:\n";
	for(int i = 1; i < argc; ++ i)
		*log_file << i << "\t" << argv[i] << endl;
	cout << "program_id:\n" << log_id << endl;
#endif
}

void LogMgr::done(){
#ifdef LOG_ON
	log_file->close();
#endif
	delete[] log_file;
}

void LogMgr::time_start(){
	time(&s);
	timeinfo = localtime (&s); 
#ifdef LOG_ON
	*log_file << "start time:\n" << asctime (timeinfo);
#endif
	cout << "start time:\n" << asctime (timeinfo);
}

void LogMgr::time_end(){
	time(&e);
	timeinfo = localtime (&e); 
	double dif = difftime (e,s);
#ifdef LOG_ON
	*log_file << "end time:\n" << asctime (timeinfo);
	*log_file << "time cost:" << dif << " seconds" << endl;
#endif
	cout << "end time:\n" << asctime (timeinfo);
	cout << "time cost:" << dif  << " seconds"<< endl;

}

void LogMgr::verbose(string str){
#ifdef LOG_ON
	*log_file << str;
#endif
	cout << str;
}

void LogMgr::record(string str){
#ifdef LOG_ON
	*log_file << str;
	log_file->flush();
#endif
}
void LogMgr::print_conf(){
#ifdef LOG_ON
	map<string, string>::iterator itr;
	for(itr = Config::confMap.begin(); itr != Config::confMap.end(); ++ itr)
		*log_file << (*itr).first << "=" << (*itr).second << endl;
#endif
}